package com.nord.Login;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;

import com.nord.R;
import com.nord.Menus.Menus;
import com.nord.R.id;
import com.nord.R.layout;
import com.nord.Services.SQLiteAdapter;
import com.nord.WebTools.HtmlBrowser;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;

import android.graphics.Typeface;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class Login extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		final EditText username = (EditText) findViewById(R.id.username);
		final EditText password = (EditText) findViewById(R.id.password);
		final Button submit = (Button) findViewById(R.id.submit);
		Button menuBanner = (Button) findViewById(R.id.menuBanner);
		Typeface tf = Typeface.createFromAsset(getAssets(), "DaysOne-Regular.ttf");
		menuBanner.setTypeface(tf);
		submit.setOnClickListener(new View.OnClickListener() {
			/*
			 * We have submitted login credentials This function saves the
			 * session id
			 */
			@Override
			public void onClick(View v) {
				System.out.println();
				new Submit().execute(username.getText().toString(), password
						.getText().toString());
			}

		});
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	private class Submit extends AsyncTask<String, Integer, String> {
		ProgressDialog progressBar;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Login.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að skrá þig á www.nord.is/ ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();

		}

		@Override
		protected String doInBackground(String... credentials) {
			((AbstractHttpClient) HtmlBrowser.httpBrowser).getCookieStore()
					.clear();

			String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/innskra/");

			if(!htmlInfo[0].contains("Exception")) {
				List<Cookie> cookies = ((AbstractHttpClient) HtmlBrowser.httpBrowser)
						.getCookieStore().getCookies();
				List<NameValuePair> loginInfo = new ArrayList<NameValuePair>(3);
		
				loginInfo.add(new BasicNameValuePair("username", credentials[0]));
				loginInfo.add(new BasicNameValuePair("password", credentials[1])); 
				loginInfo.add(new BasicNameValuePair("csrfmiddlewaretoken", cookies.get(0).getValue()));
				
				htmlInfo = HtmlBrowser.postExecutor("https://www.nord.is/innskra/", loginInfo);
				if (htmlInfo[1].compareTo("IN") == 0) {
					String fullname = HtmlBrowser.findFullName(credentials[0]);
					if(fullname.length() != 0){
						SQLiteAdapter sql = new SQLiteAdapter(Login.this);
						sql.open("W");
						sql.deleteAll("cookies");
						sql.deleteAll("user");
								
						for (int i = 0; i < cookies.size(); i++) {
							ContentValues contentValues = new ContentValues();
							contentValues.put("version", String.valueOf(cookies.get(i).getVersion()));
							contentValues.put("name", cookies.get(i).getName().toString());
							contentValues.put("value", cookies.get(i).getValue().toString());
							contentValues.put("domain", cookies.get(i).getDomain().toString());
							contentValues.put("path", cookies.get(i).getPath().toString());
							contentValues.put("expdate", formatCookie(cookies.get(i).getExpiryDate().toString()));
							sql.insert("cookies",contentValues);
						}
						
						ContentValues contentValues = new ContentValues();
						contentValues.put("username", credentials[0]);
						contentValues.put("fullname", fullname);
						sql.insert("user", contentValues);
						sql.close();
						return fullname;
					}
					else
						return "LoginException";
				}
				else
					return "LoginException";
			}
			else 
				return "UnknownHostException";
		}
		
		
		private String formatCookie(String cookie){
			String cookieArray[] = cookie.split(" ");
			cookieArray[1] = String.valueOf(HtmlBrowser.timeCalculus.get(cookieArray[1]));
			cookie = cookieArray[5] + " " + cookieArray[1] + " " + cookieArray[2] + " " + cookieArray[3];
			return cookie;
		}
		
		@Override
		protected void onPostExecute(String username) {
			progressBar.dismiss();

			if (!username.contains("Exception")) {
				Intent Menus = new Intent(Login.this, Menus.class);
				Menus.putExtra("USERNAME", username);
				startActivity(Menus);
			} else {
				String error;
				if (username.contains("UnknownHostException")) {
					error = "Ekkert netsamband";
				} else {
					error = "Rangt Lykilorð eða notendanafn";
				}
				Toast toast = Toast.makeText(Login.this, error,
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}
}
